<!--请假申请-->
<template>
  <div class="log">
    <basic-container>
      <avue-crud
          ref="crud"
          :data="tableData"
          :option="tableOption"
          :page.sync="page"
          :table-loading="tableLoading"
          @search-reset="searchReset"
          @on-load="getList"
          @search-change="searchChange"
          @size-change="sizeChange"
          @current-change="currentChange">
        <template slot="property" slot-scope="scope">
          <el-tag  v-if="scope.row.property === 0" type="success">{{ scope.label }}</el-tag>
          <el-tag  v-else-if="scope.row.property === 1" type="danger">{{ scope.label }}</el-tag>
        </template>
        <template slot="phone" slot-scope="scope">
          <p style="margin: 0" v-if="scope.row.eye === false">{{scope.row.phone}}
            <i class="icon-huabanfuben" style="margin:0 0 0 5px;font-size: 15px!important;" @click="showPhone(scope)"/>
          </p>
          <p style="margin: 0" v-if="scope.row.eye === true">{{scope.row.phone1}}
            <i class="icon-yanjing1" style="margin:0 0 0 5px;font-size: 14px!important;" @click="showPhone(scope)"/>
          </p>
        </template>
        <template slot="menu" slot-scope="scope">
          <!--自定义按钮-->
          <el-button
              class="filter-item"
              icon="el-icon-edit"
              size="mini"
              type="primary"
              @click="handle(scope.row)">请假申请
          </el-button>
        </template>
      </avue-crud>
      <!--请假申请弹窗-->
      <el-dialog
          :visible.sync="dialogEditVisible"
          title="请假申请"
          width="40%"
          @close="dictItemVisible"
          :close-on-click-modal="false">
        <el-form :rules="rules">
          <el-form-item prop="leaveType" label="选择请假类型" >
              <el-radio v-model="leaveType" label="0">事假</el-radio>
              <el-radio v-model="leaveType" label="2">晚休</el-radio>
          </el-form-item>
          <el-form-item prop="startTime" label="开始时间">
            <el-col :span="12">
              <el-date-picker
                  v-model="startTime"
                  type="datetime"
                  placeholder="请选择开始时间"
                  format="yyyy-MM-dd HH:mm"
                  value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </el-col>
          </el-form-item>
          <el-form-item prop="endTime" label="结束时间">
            <el-col :span="12">
              <el-date-picker
                  v-model="endTime"
                  type="datetime"
                  :placeholder="dialogStatus ==='view'?'':'请选择结束时间'"
                  :picker-options="endDatePicker"
                  :disabledDate="this.startTime"
                  :disabled="dialogStatus ==='view'"
                  format="yyyy-MM-dd HH:mm"
                  value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </el-col>
          </el-form-item>
          <el-form-item label="请假时长" >
            <el-col :span="12">
              <p style="margin: 0">{{durationDay}}天{{durationHour}}时</p>
            </el-col>
          </el-form-item>

          <el-form-item prop="createUser" label="发起人">
            <el-col :span="12">
              <el-select v-model="value" value-key="value" placeholder="请选择" style="margin-left: 14px">
                <el-option
                    v-for="item in userOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item">
                </el-option>
              </el-select>
            </el-col>
          </el-form-item>

          <el-form-item prop="cause" label="请假事由">
            <el-col :span="12">
              <el-input v-model="cause" type="textarea" :rows="4" placeholder="请输入请假事由" ></el-input>
            </el-col>
          </el-form-item>
          <el-form-item>
            <el-col :span="24">
              <el-button
                  class="filter-item"
                  size="small"
                  type="primary"
                  style="float: right;margin:4px 20px 4px 0"
                  @click="handleUpdate()">提交
              </el-button>
            </el-col>
          </el-form-item>
        </el-form>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
import {EditindexcreateUserObj, EditndexObj, indexObj} from '@/api/leave/index'
import {mapGetters} from 'vuex'
import {LEAVE_DETAILS, LEAVE_PROPERTY, LEAVE_SEX, STUDENT_IDE} from '@/const/Leave'
import {PASS_DETAILS} from "@/const/Dict";

export default {
  name: 'apply',
  data() {
    return {
      phone:'',  //打码手机号
      phone1:'', //未打码手机号
      dialogStatus:'',
      endDatePicker: this.processDate(),  //结束时间大于开始时间
      time:[],
      fileList: [],
      dialogEditVisible:false,
      tableData: [],
      searchForm: {},
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      tableLoading: false,
      createUser:'',
      startTime:'',
      endTime:'',
      leaveType:'',
      cause: '',
      rules: {  //必填项（验证规则）
        createUser: [
          {required: true, trigger: "none"}
        ],
        leaveType: [
          {required: true, trigger: "none"}
        ],
        startTime: [
          {required: true, trigger: "none"}
        ],
        endTime: [
          {required: true, trigger: "none"}
        ],
        cause: [
          {required: true, trigger: "none"}
        ],
      },
      userOptions: [{
        value:'',
        label: '',
      }],
      value:'',
       tableOption:{
         border: true,  //竖线边框
         index: true,  //表格序号
         indexLabel: '序号',  //序号的标题
         stripe: true,  //是否显示表格的斑马条纹
         menuWidth: 180,  //操作菜单栏的宽度
         align: 'center',  //表格列对其方式
         emptyBtnText: '重置', //清空按钮文案
         searchMenuSpan: 6,  //搜索及清空等操作按钮一栏长度
         delBtn: false,  //行内删除按钮
         editBtn: false,  //行内编辑按钮
         menuType: 'button',//操作栏样式为按钮
         props: {
           label: 'label',
           value: 'value'
         },
         column: [
           {
             label: '人员id',  //字段标题
            prop: 'id',  //字段名称
            search: false,  //搜索是否显示
            hide: true,  //展示页面是否显示
            viewDisplay: false,  //详情时是否显示
          },
          {
            label: '姓名',
            prop: 'personName',
            search: true,
            dicData: LEAVE_DETAILS,  //引入字典
          }, {
            label: '学号',
            prop: 'number',
            search: false,
            dicData: LEAVE_DETAILS,
          }, {
            label: '性别',
            prop: 'sex',
            search: true,
            type: 'select',  //搜索框显示类型
            dicData: LEAVE_SEX,
            change: (value) => {
              if(value.value === ''){
                return;
              }
              this.searchForm.sex = value.value
              this.getList(this.page, this.searchForm)
            },
          },{
             label: '校区',
             prop: 'campusDeptArea',
             dicData: PASS_DETAILS,
             editDisplay: false,
           }, {
            label: '年级',
            prop: 'parentName',
            search: false,
            type: 'select',
            dicData: LEAVE_DETAILS,
          },
          {
            label: '年级',
            prop: 'deptId',
            search: true,
            type: 'select',
            hide: true,
            defaultExpandAll: true,
            dicUrl: '/admin/dept/PermissionTree',
            cascaderItem: ['deptName'],
            dicFormatter: (res) => {
              let gradeArr = res.data
              let value = []
              if(gradeArr.length> 0){
                for(let i of gradeArr){
                  if(i.typeNum == "2" && i.isLock === false){
                    value.push(i)
                  }
                }
                console.log(value)
                return value
              }
            },
            dicMethod: 'get',
            props: {
              label: 'name',
              value: 'id'
            },
            change: (value) => {
              this.searchForm.deptId = value.value
              this.getList(this.page, this.searchForm)
            },
          },
          {
            label: '班级',
            prop: 'deptName',
            search: true,
            filter: false,
            type: 'select',
            defaultExpandAll: true,
            dicUrl: '/campus/sysdept/detpTree/{{key}}/1,2,3',
            dicFormatter: (res) => {
              return res.data[0].children;//返回字典的层级结构
            },
            dicMethod: 'get',
            props: {
              label: 'name',
              value: 'deptId',
            },
            change: (value) => {
              this.searchForm.deptId = value.value
              this.getList(this.page, this.searchForm)
            },
          },
          {
            label: '学生属性',
            prop: 'identityKey',
            search: true,
            type: 'select',
            dicData: STUDENT_IDE,
            change: (value) => {
              if(value.value === ''){
                return;
              }
              this.searchForm.identityKey = value.value
              this.getList(this.page, this.searchForm)
            },
          }, {
            label: '楼栋',
            prop: 'buildingName',
            dicData: LEAVE_DETAILS,
          },{
            label: '楼栋',
            prop: 'buildingId',
            hide: true,
            search: true,
            type: 'select',
            dicUrl: '/campus/building/selectAll',
            dicMethod: 'get',
            props: {
              label: 'buildingName',
              value: 'buildingId'
            },
            change: (value) => {
              if(value.value === ''){
                return;
              }
              this.searchForm.buildingId = value.value
              this.getList(this.page, this.searchForm)
            },
          }, {
            label: '宿舍号',
            prop: 'dormNumber',
            dicData: LEAVE_DETAILS,
            search: true,
            type: 'input',
          },{
            width: 100,
            label: '人脸照片',
            prop: 'photoId',
            type: 'upload',
            listType: 'picture-img',
            propsHttp: {
              home: '/campus/persons/photo/'
            },
          }, {
            label: '家长联系电话',
            prop: 'phone',
            viewDisplay: true,
            slot: true, //加隐藏显示手机号
            search: false,
             width: 118,
            dicData: LEAVE_DETAILS,
          },{
            label: '状态',
            prop: 'property',
            viewDisplay: true,
            search: false,
            slot:true,  //加tag标签
            type: 'select',
            dicData: LEAVE_PROPERTY,
            change: (value) => {
              if(value.value === ''){
                return;
              }
              this.searchForm.property = value.value
              this.getList(this.page, this.searchForm)
            },
          },{
            label: '信息修改时间',
            prop: 'updateTime',
            type: 'datetime',
            width: 120,
            format: 'yyyy-MM-dd HH:mm',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            viewDisplay: false,
            search: false,
            dicData: LEAVE_DETAILS,
          },
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['permissions','userInfo']),
    //获取请假时长天数
    durationDay() {
      console.log('调用computed')
      if (this.endTime && this.startTime !== ''){
        let endDate = new Date(this.endTime);
        let startDate = new Date(this.startTime);
        var stopDays = parseInt(Math.abs(endDate - startDate) / (24 * 3600 * 1000));
        return stopDays
      }else{
        return 0
      }
    },
    //获取请假时长小时数
    durationHour() {
      console.log('调用computed')
      if (this.endTime && this.startTime !== ''){
        let endDate = new Date(this.endTime);
        let startDate = new Date(this.startTime);
        var dateDiff = endDate.getTime() - startDate.getTime();//时间差的毫秒数
        var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000));//计算出相差天数
        var leave1 = dateDiff % (24 * 3600 * 1000)    //计算天数后剩余的毫秒数
        var hours = Math.floor(leave1 / (3600 * 1000))//计算出小时数
        return hours
      }else{
        return 0
      }
    },
  },
  methods: {
    //手机号点击眼睛显示隐藏
    showPhone(scope){
      // debugger
      if(scope.row.eye === false){
        scope.row.eye = true  //显示手机号
      }else if(scope.row.eye === true){
        scope.row.eye = false //隐藏手机号
      }
    },

    //定义结束时间
    processDate() {
      const  self = this
      return {
        disabledDate(time) {
          if (self.startTime !== '') {  //如果开始时间不为空，则结束时间大于开始时间
            return new Date(self.startTime).getTime() > time.getTime() + 3600 * 1000 * 24
          }
        }
      }
    },

    //展示表格
    getList(page, params) {
      this.tableLoading = true
      indexObj(Object.assign({
        current: page.currentPage,
        size: page.pageSize
      }, params, this.searchForm)).then(response => {
        this.tableData = response.data.data.records
        for(var i=0; i<response.data.data.records.length; i++) {
          let phone = response.data.data.records[i].phone
          if (phone !== null) {
            let newphone = phone.replace(/^(.{3})(?:\d+)(.{4})$/,"\$1****\$2");  //手机号打码正则
            response.data.data.records[i].phone = newphone //已打码
            response.data.data.records[i].phone1 = phone   //未打码
          }
        }
        this.tableData.map(item => {
          this.$set(item, 'eye')
          item.eye = false
        })
        this.page.total = response.data.data.total
        this.tableLoading = false
      })
    },

    //获取所有发起人的身份数据
    createUserOptions(){
      let param = {
        'identity':47
      }
      EditindexcreateUserObj(param).then(res => {
        if (res.data.code === 0) {
          this.userData = res.data.data;
          this.userOptions = this.userData.map(item => {
            return {value:`${item.phone}`,label: `${item.name}`};
          })
        }
      });
    },

    //请假申请弹窗
    handle: function (row) {
      this.dialogEditVisible = true
      this.leaveType = null
      this.startTime = null
      this.endTime = null
      this.cause = null
      this.currentrow = row
      this.createUserOptions()
    },

    //关闭弹窗
    dictItemVisible: function () {
      this.dialogEditVisible = false
      this.value = null
    },

    //请假申请提交
    handleUpdate: function () {
      var date = new Date();
      var year=date.getFullYear();
      /* 在日期格式中，月份是从0开始的，因此要加0
       * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
       * */
      var month= date.getMonth()+1<10 ? "0"+(date.getMonth()+1) : date.getMonth()+1;
      var day=date.getDate()<10 ? "0"+date.getDate() : date.getDate();
      var hours=date.getHours()<10 ? "0"+date.getHours() : date.getHours();
      var minutes=date.getMinutes()<10 ? "0"+date.getMinutes() : date.getMinutes();
      var seconds=date.getSeconds()<10 ? "0"+date.getSeconds() : date.getSeconds();
      // 拼接时间
      this.doctorApproveTime = year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds;
      if(this.leaveType === null){
        this.$message.error('提交失败,请选择请假类型')
        return;
      }
      if(this.startTime === null){
        this.$message.error('提交失败,请选择开始时间')
        return;
      }
      if(this.endTime === null){
        this.$message.error('提交失败,请选择结束时间')
        return;
      }
      if(this.startTime >= this.endTime){
        this.$message.error('提交失败,请假结束时间需大于开始时间')
        return;
      }
      if(this.value.label === undefined){
        this.$message.error('提交失败,请选择发起人')
        return;
      }
      if(this.cause === null){
        this.$message.error('提交失败,请输入请假事由')
        return;
      }
      let param = {
        'createUser':'生活老师'+this.value.label,
        'personId':this.currentrow.id,
        'linkPhone':this.value.value,
        'deptId':this.currentrow.deptId,
        'leaveType':this.leaveType,
        'startTime':this.startTime,
        'endTime':this.endTime,
        'cause':this.cause,
        'leaveStatus':0,
        'durationDay':this.durationDay,
        'durationHour':this.durationHour,
        'parentApprove' : 1,
        'parentApproveTime': this.doctorApproveTime,
        'parentApproveAdvice' : '生活老师'+this.value.label+'：发起请假',
      }
      EditndexObj(param).then(res => {
          this.getList(this.page)
          this.dialogEditVisible = false
          this.$message.success('提交成功！')
          this.leaveType = null
          this.startTime = null
          this.endTime = null
          this.cause = null
          this.value = null
      })
    },

    //搜索页面内容
    searchChange(form, done) {
      if (form.deptName !== undefined) {
        form.deptId = form.deptName
        this.getList(this.page, form)
        done()
      }
      this.searchForm = form
      this.page.currentPage = 1
      this.getList(this.page, form)
      done()
    },

    //点击每页多少条会调size-change方法回调
    sizeChange(pageSize) {
      this.page.pageSize = pageSize
    },

    //点击页码会调用current-change方法回调当前页
    currentChange(current) {
      this.page.currentPage = current
    },

    //清空时重置页面
    searchReset(){
      this.searchForm = {};
      this.getList(this.page)
    }
  }
}
</script>
<style>
.spacing{
  margin-left: 27px;
}
</style>
<style scoped>
/deep/.avue-crud__menu{
  display: none;
}

/deep/ .el-form-item__label {
  text-align: left;
}

/deep/ .avue-form__row {
  padding-left: 2px !important;
  padding-right: 36px !important;
}

/deep/ .avue-form__menu--center {
  text-align: left;
}
</style>
